package server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {
    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    public RequestProcessor(Socket socket,Map<String,HttpServlet> servletMap){
        this.socket = socket;
        this.servletMap = servletMap;
    }
    @Override
    public void run() {
        String host = "";
        try {
            HttpServlet httpServlet = null;
            InputStream inputStream = this.socket.getInputStream();//输入流
            OutputStream outputStream = this.socket.getOutputStream();//输出流
            Request request = new Request(inputStream);
            String url = request.getUrl();
            for (Map.Entry<String, HttpServlet> entry : this.servletMap.entrySet()) {
                String key = entry.getKey();
                host = key.split(url)[0];
                if((host+url).equalsIgnoreCase(key)){
                    httpServlet = entry.getValue();
                    break;
                }
            }
            Response response = new Response(outputStream);
            //判断是不是请求动态资源
            if(httpServlet==null){//静态的
                response.outputHtml(url);
            }else{//动态资源请求
                httpServlet.service(request,response);
            }
            socket.close();
        } catch (Exception e){
            e.printStackTrace();
        }

    }
}
